//
//  DataManager.m
//  OrderOnline
//
//  Created by YAPPA_3 on 11/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DataManager.h"
#import "DMUnit.h"
#import "DMCommon.h"


@implementation NSData(extend)
- (NSData*)convertXml
{
	NSString* base_str = [[[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding] autorelease];
	NSString* conv_str = [base_str stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
	return [conv_str dataUsingEncoding:NSUTF8StringEncoding];
}
@end

@implementation DataManager
@synthesize m_Current;
@synthesize m_CacheManager;
@synthesize m_Downloader;
@synthesize m_XmlParser;
@synthesize m_IsOffline;
@synthesize m_listOrder;
@synthesize m_listOrderCount;
@synthesize m_order;
static DataManager* gInstance = nil;

static const NSString* typeNames[eDmtMax] =
{
	@"DMMenuFood",
};

- (id)init{
	self = [super init];
	if ( self ) {
		m_Current			 = [[DMCurrentInfo	 alloc] init];
		m_CacheManager	     = [[CacheController alloc] init];
		m_Downloader		 = [[Downloader		 alloc] init];
		m_XmlParser			 = [[OrderXmlParser	 alloc] init];
		m_listOrder			 = [[NSMutableArray alloc] init];
		m_listOrderCount	 = [[NSMutableArray alloc] init];
		m_order				 = [[Order alloc] init];
		m_DMUnits = [[NSMutableArray alloc] init];
		for(int i = 0 ; i < eDmtMax ; i ++){
			NSString* name = (NSString *)typeNames[i];
			Class c = NSClassFromString(name);
			DMUnit* unit = [[c alloc] init];
			[unit setOwner:self];
			[m_DMUnits addObject:unit];
		}	
	}
	
	return self;
}

-(void)dealloc
{
	SAFE_RELEASE(m_Current);
	SAFE_RELEASE(m_CacheManager);
	SAFE_RELEASE(m_Downloader);
	SAFE_RELEASE(m_XmlParser);
	SAFE_RELEASE(m_listOrder)
	SAFE_RELEASE(m_listOrderCount)
	SAFE_RELEASE(m_order)
	[super dealloc];
}

- (void)update
{
	if( m_IsOffline == YES )
		return;
	
	[m_Downloader update];
	
	return;
}

- (id)getDMUnit:(eDataManagerType)dmtype
{
	DMUnit* unit = [m_DMUnits objectAtIndex:dmtype];
	[unit setXmlParser:m_XmlParser];
	[unit setCurrent:m_Current];
	return unit;
}

- (BOOL)isExistInResource:(NSString *)url
{
	BOOL ret = NO;
	if (( url != nil )
		&& ( ! [url isEqualToString:TEXT_SPACE] )
		&& ( checkURLPathType( url ) == URLPATH_TYPE_NORMAL ))
	{
		NSString* resName = [[NSBundle mainBundle] pathForResource:[[url lastPathComponent] stringByDeletingPathExtension]
															ofType:[url pathExtension]
													   inDirectory:[url stringByDeletingLastPathComponent]];
		DebLog(@"ResourceName=%@",resName);
		ret = ( resName != nil );
	}
	return( ret );
}
- (NSData *)loadFromResource:(NSString *)url
{
	NSData* data = nil;
	if (( url != nil )
		&& ( ! [url isEqualToString:TEXT_SPACE] )
		&& ( checkURLPathType( url ) == URLPATH_TYPE_NORMAL ))
	{
		NSString* resName = [[NSBundle mainBundle] pathForResource:[[url lastPathComponent] stringByDeletingPathExtension]
															ofType:[url pathExtension]
													   inDirectory:[url stringByDeletingLastPathComponent]];
		DebLog(@"ResourceName=%@",resName);
		data = [NSData dataWithContentsOfFile:resName];
	}
	return( data );
}


- (NSString *)createServerPath:(NSString *)path
{
	return [self createServerPath:path current:m_Current];
}

- (NSString *)createServerPath:(NSString *)path current:(DMCurrentInfo*)current
{
	NSString* name = nil;
	if ( path )
	{
		int type = checkURLPathType( path );
		switch( type )
		{
			case  URLPATH_TYPE_NORMAL:
				if ( current.root )
					name = [NSString stringWithFormat:@"%@/%@/%@", current.root.path, current.path, path];
				break;
			case  URLPATH_TYPE_HTTP:
				name = [NSString stringWithString:path];
				break;
		}
	}
	return( name );
}

- (DLResponse)requestDownload:(NSString*)url_path saveName:(NSString*)save_name delegate:(id)delegate priority:(int)priority
{
	// NG
	if( (m_IsOffline == YES)		
	   || (url_path == nil)			
	   || (save_name == nil)
	   || (delegate == nil)
	   )
	{
		return DL_RESPONSE_NG;
	}
	
	return [m_Downloader requestDownload:url_path saveName:save_name delegate:delegate priority:priority];
}

- (BOOL) addFoodToOrder: (Food*) food count: (int) countNum
{
	BOOL isEdit = NO;
    if ([m_order.m_listFoodOrder count]) {
        for (int i = 0; i < [m_order.m_listFoodOrder count]; i++) {
            FoodOrder* foodOrder = [m_order.m_listFoodOrder objectAtIndex:i];
            if ([foodOrder.m_productID isEqualToString:food.m_productID]) {
                foodOrder.m_count = countNum;
				isEdit = YES;
                break;
            }
            else if(i == [m_order.m_listFoodOrder count] - 1)
            {
				FoodOrder* foodOrder1 = [[FoodOrder alloc] init];
				foodOrder1.m_count = countNum;
				foodOrder1.m_linkImage = food.m_linkImage;
				foodOrder1.m_productID = food.m_productID;
				foodOrder1.m_title = food.m_title;
				foodOrder1.m_type = food.m_type;
				foodOrder1.m_price = food.m_price* countNum;
                [m_order.m_listFoodOrder addObject:foodOrder1];
                [foodOrder1 release];
            }            
        }
    }
    else
    {
		FoodOrder* foodOrder1 = [[FoodOrder alloc] init];
		foodOrder1.m_count = countNum;
		foodOrder1.m_linkImage = food.m_linkImage;
		foodOrder1.m_productID = food.m_productID;
		foodOrder1.m_title = food.m_title;
		foodOrder1.m_type = food.m_type;
		foodOrder1.m_price = food.m_price* countNum;
		[m_order.m_listFoodOrder addObject:foodOrder1];
		[foodOrder1 release];
		
    }
    return isEdit;
}

- (void) removeFoodFromOrder: (NSString*) productID 
{
	if ([m_order.m_listFoodOrder count]) {
        for (int i = 0; i < [m_order.m_listFoodOrder count]; i++) {
            FoodOrder* foodOrder = [m_order.m_listFoodOrder objectAtIndex:i];
            if ([foodOrder.m_productID isEqualToString:productID]) {
				[m_order.m_listFoodOrder removeObjectAtIndex:i];				
                break;
			}
		}
	}
}

- (void) editFoodFromOrder: (NSString*) productID count: (int) countNum
{
	if ([m_order.m_listFoodOrder count]) {
        for (int i = 0; i < [m_order.m_listFoodOrder count]; i++) {
            FoodOrder* foodOrder = [m_order.m_listFoodOrder objectAtIndex:i];
            if ([foodOrder.m_productID isEqualToString:productID]) {				
				 foodOrder.m_count = countNum;
                break;
			}
		}
	}
}



- (void) resetOrder
{
	SAFE_RELEASE(m_order)
	m_order				 = [[Order alloc] init];
}


- (BOOL) addFoodToListOrder: (Food*) food count: (int) countNum
{
	BOOL isReplace = NO;
    if ([m_listOrder count]) {
        for (int i = 0; i < [m_listOrder count]; i++) {
            Food* foodOld = [m_listOrder objectAtIndex:i];
            if ([foodOld.m_productID isEqualToString:food.m_productID]) {
                [m_listOrderCount insertObject:[NSString stringWithFormat:@"%d", countNum] atIndex:i];
				isReplace = YES;
                break;
            }
            else if(i == [m_listOrder count] - 1)
            {
                [m_listOrder addObject:food];
                [m_listOrderCount addObject:[NSString stringWithFormat:@"%d", countNum]];
            }            
        }
    }
    else
    {
		[m_listOrder addObject:food];
		[m_listOrderCount addObject:[NSString stringWithFormat:@"%d", countNum]];
    }
    return isReplace;
}

- (void) saveFoodToListOrder
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
	NSMutableArray* countNumArray = [[NSMutableArray array] retain];
	NSMutableArray* FoodArray = [[NSMutableArray array] retain];
	
	for( int i = 0; i < [m_listOrder count]; i++ )
	{
		Food* food = [m_listOrder objectAtIndex:i];
        int countNum = [[m_listOrderCount objectAtIndex:i] intValue];
		[countNumArray addObject:food];
		[FoodArray addObject:[NSString stringWithFormat:@"%d", countNum]];
    }
	[defaults setObject:countNumArray forKey:DEFAULTS_KEY_LIST_ORDER];
	[defaults setObject:FoodArray forKey:DEFAULTS_KEY_LIST_NUM_COUNT];
	
	
	SAFE_RELEASE(countNumArray);	
    SAFE_RELEASE(FoodArray);	
	// ??
	[defaults synchronize];
   
}

- (void) loadFoodToListOrder
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
	SAFE_RELEASE(m_listOrder);
    SAFE_RELEASE(m_listOrderCount);
	m_listOrder = [[NSMutableArray alloc] init];
    m_listOrderCount = [[NSMutableArray alloc] init];
	NSMutableArray* arrayOrder = [defaults objectForKey:DEFAULTS_KEY_LIST_ORDER];
	NSMutableArray* arrayCount = [defaults objectForKey:DEFAULTS_KEY_LIST_NUM_COUNT];
    for( int i = 0; i < [arrayOrder count]; i++ )
	{
		Food* food = [arrayOrder objectAtIndex:i];
        int countNum = [[arrayCount objectAtIndex:i] intValue];
		[m_listOrder addObject:food];
		[m_listOrderCount addObject:[NSString stringWithFormat:@"%d", countNum]];
    }	
}



+ (DataManager *)Shared
{
	if( !gInstance )
	{
		gInstance = [[DataManager alloc] init];
	}
	return gInstance;
}

@end
